package com.easthome.security.filter;

import com.alibaba.fastjson.JSON;
import com.easthome.common.jwt.JwtHelper;
import com.easthome.security.custom.LoginUserHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 朱敦宇
 * @time: 2023/11/13 16:56
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if ("/admin/system/index/login".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }
        // 1、从请求头中获取token，如果请求头中不存在token，直接放行即可！由Spring Security的过滤器进行校验！
        String token = request.getHeader("token");

        if (token == null || "".equals(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 2、对token进行解析，取出其中的username
        String username = JwtHelper.getUsername(token);
        Long userId = JwtHelper.getUserId(token);
        //2.5 设置ThreadLocal
        LoginUserHelper.setUserId(userId);
        LoginUserHelper.setUserName(username);
        //3、使用userId从redis中查询对应的LoginUser对象
        String permissionStr =redisTemplate.opsForValue().get("oa:login:id:"+userId);
        List<Map> list = (List<Map>) JSON.parseObject(permissionStr, List.class);
        List<SimpleGrantedAuthority> authorityList = list.stream().map(map -> new SimpleGrantedAuthority((String) map.get("authority"))).collect(Collectors.toList());
        // 4、然后将查询到的LoginUser对象的相关信息封装到UsernamePasswordAuthenticationToken对象中，然后将该对象存储到Security的上下文对象中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorityList);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 5、放行
        filterChain.doFilter(request, response);
    }
}
